<template>
  <!-- 面包屑导航 -->
    <div style="margin-top: 20px; margin-left: 20px">
        <el-breadcrumb separator="/">
            <el-breadcrumb-item><b>请假</b></el-breadcrumb-item>
            <el-breadcrumb-item>请假</el-breadcrumb-item>
        </el-breadcrumb>
    </div>
  <div class="button-container" style="margin-top: 20px; margin-left: 20px">
      <el-button type="primary" @click="goToLeaveApply">
         请假申请<el-icon><CirclePlusFilled /></el-icon>
      </el-button>
  </div>
  <!-- 表格 -->
    <div class="table-container">
        <el-table :data="tableData" stripe style="width: 100%;">
            <el-table-column prop="leaveType" label="请假类型" width="190px" />
            <el-table-column prop="startTime" label="起始时间" width="190px" />
            <el-table-column prop="endTime" label="结束时间"  width="190px"/>
            <el-table-column
                    prop="context"
                    label="请假描述"
                    show-overflow-tooltip
                    width="200px"/>
            <el-table-column prop="state" label="审核状态"  width="190px">
            <template #default="scope">
                <el-button
                        plain
                        :type="getButtonType(scope.row)"

                >
                    {{ getButtonText(scope.row) }}
                </el-button>
            </template>
            </el-table-column>
            <el-table-column prop="reason" label="理由"/>
        </el-table>
    </div>
  <!-- 分页按钮 -->
    <div class="demo-pagination-block">
        <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[5, 10, 15, 20]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />
    </div>

  <!--    请假申请按钮对话框-->
    <el-dialog v-model="tableEditVisible" title="请假申请" width="500">
        <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
            <el-form-item label="请假类型" prop="leaveType">
            <el-select v-model="form.leaveType" placeholder="请选择请假类型" style="width: 200px;">
                <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                />
            </el-select>
            </el-form-item>
            <el-form-item label="起始时间" prop="startTime">
                <el-date-picker v-model="form.startTime"
                                         type="datetime"
                                         placeholder="请选择起始时间"
                                         format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker v-model="form.endTime"
                                         type="datetime"
                                         placeholder="请选择结束时间"
                                         format="YYYY-MM-DD HH:mm:ss"
            ></el-date-picker>
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
                <el-input
                        v-model="form.contact"
                        style="width: 240px"
                        placeholder="请输入联系方式"
                        clearable
                />
            </el-form-item>
            <el-form-item label="请假原因" prop="context">
                <el-input
                        v-model="form.context"
                        style="width: 240px"
                        :autosize="{ minRows: 2, maxRows: 4 }"
                        type="textarea"
                        placeholder="请输入请假原因"
                />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="reset">取消</el-button>
                <el-button type="primary" @click="submitForm">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
import {ref, onMounted, reactive} from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import {CirclePlusFilled, Plus} from "@element-plus/icons-vue";
import moment from 'moment';
import request8090 from "../../../../utils/request8090.js";
onMounted(() => {
    fetchLeaveInfo()
});
const tableData = ref([]);
// 获取请假信息
const fetchLeaveInfo = () => {
    request8090({
        url: '/student/getleaves',
        method: 'GET',
        params: { currentPage: pagination.value.currentPage, size: pagination.value.pageSize,sNumber: sessionStorage.getItem("snumber") },
    })
        .then(res => {
            if (res.data.errorCode === 200) {
                tableData.value = res.data.data.records;
                pagination.value.total = res.data.data.total;
            } else {
                ElMessage.error('获取数据失败');
            }
        })
        .catch(error => {
            console.error('请求失败:', error);
            ElMessage.error('请求失败');
        });
}
//初始化的默认分页大小
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 0
});
//显示行数大小改变时刷新页面
const handleSizeChange = (size) => {
    pagination.value.pageSize = size;
    fetchLeaveInfo();
}
//显示页数改变时刷新页面
const handleCurrentChange = (page) => {
    pagination.value.currentPage = page;
    fetchLeaveInfo();
}
//改变按钮状态
const getButtonType = (row) => {
    if (row.state === 1) {
        return 'success';
    } else if (row.state === 2) {
        return 'danger';
    } else {
        return 'info';
    }
}

// 按钮的字体显示
const getButtonText = (row) => {
    if (row.state === 1) {
        return '已批准';
    } else if (row.state === 2) {
        return '已驳回';
    } else {
        return '未审批';
    }
}
const tableEditVisible= ref(false)
// 点击请假申请按钮弹出对话框
const goToLeaveApply=()=>{
    tableEditVisible.value = true
}
// 对话框取消按钮事件
const reset=()=>{
    // 清空表单数据
        form.value=({ leaveType: '', startTime: '', endTime: '', contact: '', context: '' })
        tableEditVisible.value = false
}
 const formRef = ref();
// 对话框按钮确认事件
const submitForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            confirm();
        } else {
            ElMessage.error('请填写完整信息');
            return false;
        }
    });
};
// 对话框按钮确认事件
const confirm=()=>{

    const data = {
        snumber:sessionStorage.getItem("snumber"),
        sname:sessionStorage.getItem("name"),
        leaveType:form.value.leaveType,
        // 将前端获取的数据转换成后端接受时相同的格式
        startTime: moment(form.startTime).format('YYYY-MM-DD HH:mm:ss'),
        endTime: moment(form.endTime).format('YYYY-MM-DD HH:mm:ss'),
        contact:form.value.contact,
        context:form.value.context
    }
    // 发送请求
    request8090({
        url:'/student/submitleave',
        method:'post',
        headers: {
            'Content-Type': 'application/json'
        },
        data:JSON.stringify(data)
    }).then(res => {
        if (200==res.data.errorCode){
            ElMessage.success('申请成功');
            fetchLeaveInfo()
            reset()
        } else {
            ElMessage.error('申请失败');
        }
    })
        .catch(error => {
            console.error('请求失败:', error);
            ElMessage.error('请求失败');
        });
}
const options = [
    {
        value: '事假',
        label: '事假',
    },
    {
        value: '病假',
        label: '病假',
    },

]
// 提交申请的数据
const form = ref({
    leaveType: '',
    startTime: '',
    endTime: '',
    contact: '',
    context: ''
})

// 敏感词
const sensitiveWords = ref(['敏感词1', '敏感词2']); // 添加或修改敏感词

// 敏感词校验
const validateSensitiveWords = (rule, value, callback) => {
    const foundWord = sensitiveWords.value.find(word => value.includes(word));
    if (foundWord) {
        callback(new Error(`不能含有敏感词：“${foundWord}”`));
    } else {
        callback();
    }
};
// 校验规则
const rules = {
    leaveType: [
        { required: true, message: '请选择请假类型', trigger: 'change' },
    ],
    startTime: [
        { required: true, message: '请选择起始时间', trigger: 'change' },
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
    ],
    contact: [
        { required: true, message: '请输入联系方式', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' },
    ],
    context: [
        { required: true, message: '请输入请假原因', trigger: 'blur' },
        { validator: validateSensitiveWords, trigger: 'blur' }
    ],
};


</script>

<style scoped>

</style>
